package com.eshop.utils;

import java.awt.image.BufferedImage;
import com.google.zxing.common.BitMatrix;
import java.io.IOException;
import com.google.zxing.WriterException;
import java.io.OutputStream;
import java.awt.image.RenderedImage;
import javax.imageio.ImageIO;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.EncodeHintType;
import java.util.Hashtable;
import javax.servlet.http.HttpServletResponse;

public class RecodeUtil
{
    public static void creatRrCode(final String contents, final int width, final int height, final HttpServletResponse response) {
        final Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        try {
            final BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, (Map)hints);
            final BufferedImage image = toBufferedImage(bitMatrix);
            ImageIO.write(image, "png", (OutputStream)response.getOutputStream());
        }
        catch (WriterException e) {
            e.printStackTrace();
        }
        catch (IOException e2) {
            e2.printStackTrace();
        }
    }
    
    public static BufferedImage toBufferedImage(final BitMatrix matrix) {
        final int width = matrix.getWidth();
        final int height = matrix.getHeight();
        final BufferedImage image = new BufferedImage(width, height, 1);
        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                image.setRGB(x, y, matrix.get(x, y) ? -16777216 : -1);
            }
        }
        return image;
    }
}
